import React, { FC, useState } from 'react'
import { Layout, Row, Col, Typography, Tooltip, Modal, Tag } from 'antd'
import {
    AppstoreOutlined,
    ContainerOutlined,
    DesktopOutlined,
    MailOutlined,
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    PieChartOutlined,
    PoweroffOutlined,
    ExclamationCircleOutlined,
} from '@ant-design/icons';
import { observer } from 'mobx-react';
import { useMobxStore } from '@/mobx/store';
import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space, Divider, Button, Form } from 'antd';
import { history } from 'umi';
import MyAvatar from './MyAvatar';
import _ from 'lodash'
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import { reg } from '@/utils/validate';
import { ShowError, ShowMsg } from '@/utils/message';
import { Ajax } from '@/api/api';
import useLogout from '@/hooks/useLogout';
import { useReduxStore } from '@/redux/store';
import { changeCollapsed } from './../../redux/actions';


const { Header } = Layout
const { Text, Link, Title } = Typography;
const styles = {
    center: {
        height: '100%',
        display: 'flex',
        alignItems: 'center',
    },
    h2Style: {
        margin: '0 15px',
        color: '#123456',
        fontSize: 14,
    }
}
const MyHead: FC<any> = () => {
    const { MyData: { userInfo, changeUserInfo, roleList } } = useMobxStore()
    const [open, setOpen] = useState<boolean>(false)
    const [form] = Form.useForm()

    const [startLogout] = useLogout()
    const { state, dispatch } = useReduxStore()

    const onCancel = () => {
        setOpen(false)
        form.resetFields()
    }

    const changePass = () => {
        setOpen(true)
        form.setFieldValue('oldpass', userInfo.get('password'))
    }
    const items: MenuProps['items'] = [
        {
            key: '1',
            label: (
                <span>首页</span>
            ),
            icon: <AppstoreOutlined />
        },
        {
            key: '2',
            label: (
                <span>个人中心</span>
            ),
            icon: <DesktopOutlined />
        },
        {
            key: '3',
            label: (
                <span>公告</span>
            ),
            icon: <MailOutlined />,
        },
        {
            key: '4',
            label: (
                <span onClick={changePass}>修改密码</span>
            ),
            icon: <PieChartOutlined />,
            danger: true
        },
    ];

    const todoLogout = () => {
        Modal.confirm({
            title: '友情提示',
            icon: <ExclamationCircleOutlined />,
            content: '你真的要退出登录吗???',
            okText: '确认',
            cancelText: '取消',
            onOk() {

                history.replace('/login')
                sessionStorage.removeItem('qftoken')
                changeUserInfo({})
            }
        });
    }
    return (
        <Header style={{ background: "#ccc", padding: 15 }}>
            <Row style={{ height: '100%' }}>
                <Col span={8} style={styles.center}>
                    <span onClick={() => dispatch(changeCollapsed(!state.get('collapsed')))} style={{ marginRight: 16, cursor: 'pointer', color: "#f50", fontSize: 18 }}>
                        {state.get('collapsed') ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                    </span>
                    <Title type="success" level={3} style={{ margin: 0, color: "#f50" }}>柳工教育</Title>
                </Col>
                <Col span={8} style={styles.center}>
                    <marquee behavior="" direction="" >
                        <div style={styles.center}>
                            <h2 style={styles.h2Style}>笃志勤学 知行合一</h2>
                            <h2 style={styles.h2Style}>笃志勤学 知行合一</h2>
                            <h2 style={styles.h2Style}>笃志勤学 知行合一</h2>
                        </div>
                    </marquee>
                </Col>
                <Col span={8} style={{ ...styles.center, justifyContent: 'flex-end' }}>
                    <div className="info" style={{ padding: '0 20px', display: 'flex', alignItems: 'center' }}>
                        <Dropdown
                            menu={{ items }}
                        >
                            <span>
                                {userInfo.get('username')}
                                <DownOutlined />
                            </span>
                        </Dropdown>


                        <Space style={{ marginLeft: 15 }} >
                            {
                                roleList.size > 0 && <Tag color={roleList.find((item: any) => item.value == userInfo.get('role'))?.color} >
                                    {/* {roleList.find((item:any)=>item.value==userInfo.get('role'))?.label} */}
                                    {
                                        _.find(roleList.toJS(), (item: any) => item.value == userInfo.get('role'))?.label
                                    }
                                </Tag>
                            }
                        </Space>


                        <Space style={{ marginLeft: 15, cursor: 'pointer' }}>
                            <MyAvatar />
                        </Space>


                        <Space style={{ marginLeft: 15 }}>
                            <Tooltip placement="bottom" title={'注销登录'}>
                                <Button
                                    danger
                                    icon={<PoweroffOutlined />}

                                    onClick={() => todoLogout()}
                                    shape="circle"
                                />
                            </Tooltip>
                        </Space>
                    </div>
                </Col>
            </Row>

            <ModalForm
                title="修改密码"
                form={form}
                width={'30%'}
                open={open}
                submitter={{
                    resetButtonProps: {
                        type: 'dashed',
                    },
                    submitButtonProps: {
                        type: 'ghost',
                        style: {
                            display: 'block',
                        },
                    },
                    searchConfig: {
                        submitText: '确认修改',
                        resetText: '取消',
                    },
                }
                }
                modalProps={{
                    destroyOnClose: true,
                    onCancel: onCancel
                }}
                onFinish={async (values) => {
                    if (values.newpass !== values.oldpass) {
                        let res: any = await Ajax.changeuserinfo({
                            password: values.newpass,
                        })
                        if (res.code == 200) {
                            startLogout()
                        }
                    } else {
                        ShowMsg('新密码不能跟原始密码一致!')
                    }
                }}
                onFinishFailed={() => {
                    ShowError('密码校验失败')
                }}
            >
                <ProFormText
                    width="md"
                    name="oldpass"
                    label="旧密码"
                    placeholder="请输入旧密码"
                    disabled
                    rules={[
                        { required: true, message: '请输入' },
                        { pattern: reg.pwd, message: '请输入6-16位的数字字母的密码' }
                    ]}
                />
                <ProFormText.Password
                    width="md"
                    name="newpass"
                    label="新密码"
                    placeholder="请输入新密码"
                    rules={[
                        { required: true, message: '请输入' },
                        { pattern: reg.pwd, message: '请输入6-16位的数字字母的密码' }
                    ]}
                    hasFeedback
                />
                <ProFormText.Password
                    width="md"
                    name="dbnewpass"
                    label="确认新密码"
                    placeholder="请输入确认新密码"
                    dependencies={['newpass']}
                    hasFeedback
                    rules={[
                        { required: true, message: '请输入' },
                        { pattern: reg.pwd, message: '请输入6-16位的数字字母的密码' },
                        ({ getFieldValue }) => ({
                            validator(_, value) {
                                if (reg.pwd.test(value) && reg.pwd.test(getFieldValue('newpass'))) {
                                    if (getFieldValue('newpass') === value) {
                                        return Promise.resolve();
                                    } else {
                                        return Promise.reject(new Error('两次密码不一致'));
                                    }
                                } else {
                                    return Promise.reject(new Error(''));
                                }
                            },
                        }),
                    ]}

                />
            </ModalForm>
        </Header>
    )
}

export default observer(MyHead)

